package com.admin.utils.qiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author kuaiting
 */
@Component
@Slf4j
public class QiniuUtil {
	private static String host = "http://rhgi7zoca.hn-bkt.clouddn.com/";
	private static String accessKey = "fs36d041cTVsfZQpjcF8nYMJMH79YBmQm8_8Wkws";
	private static String secretKey = "BePLygpLgPn77kxQOqJK-HQo8Ilmb_3rgsCTPDdE";
	private static String bucket = "unishop";
	private static Auth auth = null;
	private static String upToken = null;
	private static Region region = null;
	private static Configuration cfg = null;

	static {
		// 默认加载一次
		auth = Auth.create(accessKey, secretKey);
		upToken = auth.uploadToken(bucket);
		region = Region.region2();
		//构造一个带指定 Region 对象的配置类
		cfg = new Configuration(region);
	}

	public static String uploadFile(MultipartFile file,String newName) throws IOException {

		UploadManager uploadManager = new UploadManager(cfg);

		try {
			Response response = uploadManager.put(file.getInputStream(), newName, upToken, null, null);
			//解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			return host + putRet.key;
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				log.error(r.bodyString());
			} catch (QiniuException ex2) {
				log.error(ex2.error());
			}
		}
		return null;
	}


	public static String uploadBigFile(MultipartFile file,String newName) {

		// 指定分片上传版本
		cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
		// 设置分片上传并发，1：采用同步上传；大于1：采用并发上传
		cfg.resumableUploadMaxConcurrentTaskCount = 6;
		UploadManager uploadManager = new UploadManager(cfg);

		try {
			Response response = uploadManager.put(file.getInputStream(), newName, upToken, null, null);
			//解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			return host + putRet.key;
		} catch (QiniuException ex) {
			Response r = ex.response;
			try {
				log.error(r.bodyString());
			} catch (QiniuException ex2) {
				log.error(ex2.error());
			}
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		return null;


	}


	public static boolean deletFile(String newName) {
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
			bucketManager.delete(bucket, newName);
			return true;
		} catch (QiniuException ex) {
			//如果遇到异常，说明删除失败
			log.error(ex.error());
			return false;
		}
	}
}
